//
//  GoodListViewController.m
//  DoneTask
//
//  Created by NeiQuan on 16/7/29.
//  Copyright © 2016年 Mr-yuwei. All rights reserved.
//

#import "GoodListViewController.h"
#import "YWStaticPublicHeader.h"
#import "YWHeader.h"
#import "HomePageTableViewCell.h"
#import "GoodPageModel.h"
#import "HomePageController.h"
#import "GoodListDataManger.h"
#import "NSString+YWExtension.h"
#import <SafariServices/SafariServices.h>
#include <objc/runtime.h>
#import "JPUSHService.h"
//#import "JJSDK.h"
//#import "JJDiamondConstants.h"
#import "JOJOWangSDK.h"
#import "JOJOWangDiamondConstants.h"
#import "YWStaticPublicHeader.h"

static const void *YWGoodLaunchAlertKey = &YWGoodLaunchAlertKey;
@interface GoodListViewController ()<UITableViewDelegate,UITableViewDataSource>{
    
    UITableView         *_tableView;
    NSMutableArray      *_listArray;
    NSInteger           _page;
}
@end
@implementation GoodListViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"省钱买";
    self.automaticallyAdjustsScrollViewInsets=NO;
    [self.view setBackgroundColor:[ UIColor  colorWithString:@"f2f2f2"]];
    _listArray=[[ NSMutableArray alloc] init];
    [self makeSubViews];
    __weak typeof(self)wekself=self;
    [[ NSNotificationCenter defaultCenter] addObserver:wekself selector:@selector(loadSystemconfig) name:@"haveLogin" object:nil];
    [[ NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showalert) name:@"alertNotice" object:nil];

    
}
-(void)showalert{
    
    if ([ NSString StringIsNULL:[ NSString idfa]])
    {
        UIAlertView *alert=   [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"省钱买a要访问你的广告跟踪,否则会影响正常的使用!请在设置->隐私->广告,关闭限制广告跟踪权限" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alert show];
        
    }
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self SetUPuserConfig];
}
-(void)SetUPuserConfig{
    
    UIWindow *window=[ UIApplication sharedApplication].keyWindow;
    
    for (UIView *view   in window.subviews )
    {
        
        if ([view isKindOfClass:[ UIAlertView class]])
        {
            [view  removeFromSuperview];
        }
    }
    
    if ([ NSString StringIsNULL:[ NSString idfa]])
    {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"省钱买a要访问你的广告跟踪,否则会影响正常的使用!请在设置->隐私->广告,关闭限制广告跟踪权限" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                    [alert show];
    }else{

        if (![[ NSUserDefaults standardUserDefaults] boolForKey:userlogin])//不知道能否被注册
        {
            NSDictionary *parameters=@{@"deviceBrand":@"苹果手机",@"deviceModel":[NSString phoneModel],@"idfa":[ NSString idfa],@"ip":[NSString getIPAddress],@"mac":[NSString  macaddress],@"network":@([ NSString getNetWorkStates]),@"openudid":[ NSString  createUUID],@"systemVersion":[NSString deviceVersion],@"type":@"1",@"imei":@""};
            [GoodListDataManger  netWorkGetWithDataType:NetworkDatalaunchType parameters:parameters SuccessBlock:^(NSDictionary *dic)
             {
                 if ([dic[@"code"]integerValue]==0)//创建用户成功   //每次进入APP时都需要调用，创建成功则返回唯一新设备Id，失败返回旧设备Id
                 {
                     [[ NSUserDefaults standardUserDefaults] setObject:[dic[@"response"] stringValue] forKey:userId];//保存用户id
                     [[ NSUserDefaults standardUserDefaults] synchronize];
                      [[ NSUserDefaults standardUserDefaults] setBool:YES forKey:userlogin];
                     [[ NSNotificationCenter defaultCenter] postNotificationName:@"haveLogin" object:nil];//告诉用户已经可以启动
                 }
                 
             }];
        }
    }
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=Privacy&path=Photos"]]
    if (buttonIndex!=0)
    {
        NSURL *url = [NSURL URLWithString:@"prefs:root=Privacy"];
        if ([[UIApplication sharedApplication] canOpenURL:url])
        {
            [[UIApplication sharedApplication] openURL:url];
        }
 
    }
}
-(void)makeSubViews{
    
    __weak typeof(self)wakself=self;
    UIButton *btn=[ UIButton buttonWithType:UIButtonTypeCustom];
    [btn setFrame:CGRectMake(0, 0, 25, 25)];
    [btn setBackgroundImage :[ UIImage imageNamed:@"刷新"] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem=[[ UIBarButtonItem alloc] initWithCustomView:btn];
    [btn addTarget:wakself action:@selector(clickrefresh) forControlEvents:UIControlEventTouchUpInside];

    UITableView *tableView=[[ UITableView alloc] initWithFrame:CGRectMake(0, 0, YWWidth, self.view.frame.size.height-64) style:UITableViewStylePlain];
    tableView.delegate=self;
    tableView.dataSource=self;
    tableView.tableFooterView=[[ UIView alloc] init];
    _tableView=tableView;
    [self.view addSubview:tableView];
     _page=0;
    [self loadData:_page];
      
}
-(void)clickrefresh{
    _page++;
    [self loadData:_page];
}
-(void)loadData:(NSInteger)index{
    //POST goods/query 商品查询 //pageNum integer 页码 //pageSize integer 页大小
   [self showMBProgressHUDLoadinginView:self.view];
    NSDictionary *dic=@{@"pageNum":@(index),@"pageSize":@"10"};
    [NetWorkRequest netWorkPOSTWithURLString:@"goods/query" parameters:dic SuccessBlock:^(NSDictionary *dic)
    {
        [self removeMBProgressView];
        if ([dic[@"code"]integerValue]==0)
        {
            if (index==0&&_listArray.count!=0)[_listArray removeAllObjects];
            [_listArray addObjectsFromArray: [ GoodPageModel mj_objectArrayWithKeyValuesArray:dic[@"response"]]];
            [_tableView reloadData];
        }
    } failBlock:^(NSError *error)
    {
      [self removeMBProgressView];
      [self showMBProgressHUDNetErrorMessage:@"请查看你的网络" inView:self.view];
    }];
}
//http://192.168.0.136:8080
//http://1515.cn:8080/yproject/h5/html/index.jsp
//http://123.56.94.5:8091
-(void)loadSystemconfig{
    //
     NSString *string=[[ NSUserDefaults standardUserDefaults] objectForKey:userId];//用户ID
   //  NSString *tokenID=[[ NSUserDefaults standardUserDefaults] objectForKey:@"userDeviceToken"];//推送
    if (![ NSString StringIsNULL:string]&&![NSString StringIsNULL: [NSString idfa]]&&![NSString StringIsNULL:[JPUSHService registrationID]])
    {
        NSString *version = [[[NSBundle mainBundle] infoDictionary]objectForKey:@"CFBundleShortVersionString"];//获取版本号
        NSDictionary *parameters=@{@"id":string,@"clientVersion":version,@"type":@"1"};
        [GoodListDataManger  netWorkGetWithDataType:NetworkDatasystemOpentype parameters:parameters SuccessBlock:^(NSDictionary *dic){
            if ([dic[@"code"]integerValue]==0)
            {
                if ([dic[@"response"][@"iosAllowFullFunction"]integerValue]==1)//http://1515.cn:8080/yproject/api/
                {
                    //http://www.neiquan.net:8113/yproject/h5/html/index.jsp?type=1&idfa=%@
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[ NSString stringWithFormat:@"%@/yproject/h5/html/index.jsp?type=1&idfa=%@",baseurl,[ NSString idfa]]]];
                    //https://itunes.apple.com/cn/app/shou-ji-bai-du-hai-liang-xin/id382201985?mt=8
                }
            }
        }];
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return _listArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    HomePageTableViewCell  *cell=[ tableView dequeueReusableCellWithIdentifier:@"goodListcell"];
    if (cell==nil)
    {
        cell=[[ NSBundle mainBundle] loadNibNamed:@"HomePageTableViewCell" owner:self options:nil][0];
    }
    GoodPageModel *model=_listArray[indexPath.row];
    cell.model=model;
    return cell;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    GoodPageModel *model=_listArray[ indexPath.row];
    return [NSString sizeWithString:model.title font:[UIFont systemFontOfSize:14] constrainedToWidth:YWWidth-30].height+400*YWYsale;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    HomePageController *detail=[[HomePageController alloc] init];
    GoodPageModel *model=_listArray[ indexPath.row];
    detail.neswID=model.id;
    [self.navigationController pushViewController:detail animated:YES];
}
-(void)dealloc{
    
    [[ NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
